package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserJob;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.DialogTypeUtils;
import com.zhiqianbao.utils.DialogWorkIndustryTypeUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.WorkIndustryDataUtils;
import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2015/12/30.
 */
public class UpdateJobActivity extends BaseActivity{
    /**
     * 职位编辑框
     */
    EditText editTextDuty;
    /**
     *
     */
    EditText editTextDutyKey;
    /**
     * 单位名称编辑框
     */
    EditText edittextUnitName;
    /**
     * 所在城市编辑框
     */
    EditText edittextThecity;
    /**
     * 单位地址编辑框
     */
    EditText edittextUnitAddressRough;
    /**
     * 单位电话编辑框
     */
    EditText edittextUnitAddressTel;
    /**
     * 名称
     */
    TextView textviewUnitName;
    /**
     * 地址
     */
    TextView textviewUnitAddressRough;
    /**
     * 电话
     */
    TextView textviewUnitAddressTel;
    /**
     * 确认提交按钮
     */
    Button buttonSubmit;
    EditText editProviceText;
    EditText editCityText;
    EditText editAreaText;
    private DialogTypeUtils typeUtils;
    private EditText editText_msg;
    private String[] array_work_msg;
    int workMsgIndex = 0;
    int workMsgSecond = 0;
    String profession="";
    SharedPreferanceUtils sharedPreferanceUtils;
    WorkIndustryDataUtils dataUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_info);
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        dataUtils=new WorkIndustryDataUtils(getResources());
        init();
        initView();
        typeUtils=new DialogTypeUtils(this);
    }


    private void initView() {
         editTextDuty=(EditText)findViewById(R.id.editText_duty);
         editTextDutyKey=(EditText)findViewById(R.id.editText_duty_key);
         edittextUnitName=(EditText)findViewById(R.id.edittext_unit_name);
         edittextThecity=(EditText)findViewById(R.id.edittext_thecity);
         edittextUnitAddressRough=(EditText)findViewById(R.id.edittext_unit_address_rough);
         edittextUnitAddressTel=(EditText)findViewById(R.id.edittext_unit_address_tel);
         textviewUnitName=(TextView)findViewById(R.id.textview_unit_name);
         textviewUnitAddressRough=(TextView)findViewById(R.id.textview_unit_address_rough);
         textviewUnitAddressTel=(TextView)findViewById(R.id.textview_unit_address_tel);
         buttonSubmit=(Button)findViewById(R.id.button_submit);
         editProviceText=(EditText)findViewById(R.id.edit_provice_text);
         editCityText=(EditText)findViewById(R.id.edit_city_text);
         editAreaText=(EditText)findViewById(R.id.edit_area_text);
        //初始化数据
        Intent intent = getIntent();
        UserJob userJob = (UserJob) intent.getSerializableExtra("userJob");
        array_work_msg = getResources().getStringArray(R.array.array_work_msg);
        editText_msg = (EditText) findViewById(R.id.editText_msg);
        if (userJob!=null){
            if ("学生".equals(userJob.getJobName())) {
                textviewUnitName.setText("学校名称");
                textviewUnitAddressRough.setText("学校地址");
                textviewUnitAddressTel.setText("学校电话");
            } else {
                textviewUnitName.setText("单位名称");
                textviewUnitAddressRough.setText("单位地址");
                textviewUnitAddressTel.setText("单位电话");
            }

            editTextDuty.setText(userJob.getJobName());
            editTextDutyKey.setText(userJob.getJob());
            edittextUnitName.setText(userJob.getCompany());
            String city = "";
            if (userJob.getProvince().equals(userJob.getCity())) {
                city = userJob.getProvince() + userJob.getArea();
            } else {
                city = userJob.getProvince() + userJob.getCity() + userJob.getArea();
            }
            edittextThecity.setText(city);
            edittextUnitAddressRough.setText(userJob.getAddress());
            edittextUnitAddressTel.setText(userJob.getPhone());
            //地区信息
            editProviceText.setText(userJob.getProvince());
            editCityText.setText(userJob.getCity());
            editAreaText.setText(userJob.getArea());
            profession=sharedPreferanceUtils.getUserJobProfession();
            if(!TextUtils.isEmpty(profession)) {
                editText_msg.setText(dataUtils.getWorkMsg(profession));
                workMsgIndex=dataUtils.getOneTypeIndex();
                workMsgSecond=dataUtils.getTwoTypeIndex();
            }
        }

        ButtonListener listener = new ButtonListener();
        editTextDuty.setOnClickListener(listener);
        edittextThecity.setOnClickListener(listener);
        buttonSubmit.setOnClickListener(listener);
        editText_msg.setOnClickListener(listener);

        editTextDuty.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ("学生".equals(s.toString())) {
                    textviewUnitName.setText("学校名称");
                    textviewUnitAddressRough.setText("学校地址");
                    textviewUnitAddressTel.setText("学校电话");
                } else {
                    textviewUnitName.setText("单位名称");
                    textviewUnitAddressRough.setText("单位地址");
                    textviewUnitAddressTel.setText("单位电话");
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(R.id.editText_duty==v.getId()) {
                    //showSelectDialog(Constants.JOBS, editTextDuty, "请选择职位");
                    alertSelectDialog(Constants.CODE_WORKJOB, "请选择职位", editTextDuty, editTextDutyKey);
            }
            else if(R.id.edittext_thecity==v.getId()) {
                    if (typeUtils != null) {
                        if ((typeUtils.getOptions1Items() != null && (typeUtils.getOptions1Items().size() != 0)) &&
                                (typeUtils.getOptions2Items() != null && (typeUtils.getOptions2Items().size() != 0)) &&
                                (typeUtils.getOptions3Items() != null && (typeUtils.getOptions3Items().size() != 0))) {
                            typeUtils.showPickerView(edittextThecity, editProviceText, editCityText, editAreaText);
                        } else {
                            typeUtils.initJsonData(UpdateJobActivity.this);
                            typeUtils.showPickerView(edittextThecity, editProviceText, editCityText, editAreaText);
                        }
                    }
            }
            else if(R.id.editText_msg==v.getId()) {
                    //工作信息
                    new DialogWorkIndustryTypeUtils(UpdateJobActivity.this, dataUtils.getOptions1Items(),
                            dataUtils.getOptions2Items(), new DialogWorkIndustryTypeUtils.WorkIndustryCallBack() {
                        @Override
                        public void workInfoCallBack(int firstCode, int secondCode) {
                            workMsgIndex = firstCode;
                            workMsgSecond = secondCode;
                            editText_msg.setText(dataUtils.getFirstWorkMsg(firstCode - 1)
                                    + "—" + dataUtils.getSecondtWorkMsg(workMsgSecond));
                        }
                    });
            }
            else if(R.id.button_submit==v.getId()){
                    if (StringUtils.isBlank(editTextDuty.getText().toString())
                            || StringUtils.isBlank(editText_msg.getText().toString())
                            || StringUtils.isBlank(edittextUnitName.getText().toString())
                            || StringUtils.isBlank(edittextThecity.getText().toString())
                            || StringUtils.isBlank(edittextUnitAddressRough.getText().toString())
                            || StringUtils.isBlank(edittextUnitAddressTel.getText().toString())
                            || StringUtils.isBlank(editProviceText.getText().toString())
                            || StringUtils.isBlank(editCityText.getText().toString())
                            || StringUtils.isBlank(editAreaText.getText().toString())) {
                        showShortToast1("工作信息没有填完整");
                        return;
                    }

                    //调用修改工作信息接口
                    Map<String, String> param = new HashMap<>();
                    param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    param.put("jobKey", editTextDutyKey.getText().toString());
                    param.put("company", edittextUnitName.getText().toString());
                    param.put("province", editProviceText.getText().toString());
                    param.put("city", editCityText.getText().toString());
                    param.put("area", editAreaText.getText().toString());
                    param.put("address", edittextUnitAddressRough.getText().toString());
                    param.put("phone", edittextUnitAddressTel.getText().toString());
                    param.put("profession",String.valueOf(workMsgIndex));
                    param.put("childProfession",String.valueOf(workMsgSecond));
                    new UpdateJobAsyncTask().execute(param);
            }
        }
    }

    private class UpdateJobAsyncTask extends AsyncTask<Map, Void, Result<UserJob>> {
        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }
        @Override
        protected Result<UserJob> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/changeUserJob", params[0], UpdateJobActivity.this);
            Result<UserJob> resultObject = Result.fromJson(result, UserJob.class);
            return resultObject;
        }
        @Override
        protected void onPostExecute(Result<UserJob> result) {
            if(result!=null) {
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    showShortToast1(result.getMsg());
                    UserJob userJob = result.getData();
                    //更新数据库
                    UserJob.deleteAll(UserJob.class);
                    userJob.save();
                    String profession=userJob.getProfession();
                    String childProfession=userJob.getChildProfession();
                    if((!TextUtils.isEmpty(profession))&&(!TextUtils.isEmpty(childProfession))){
                        sharedPreferanceUtils.setUserJobProfession(profession+"-"+childProfession);
                    }
                    else{
                        sharedPreferanceUtils.setUserJobProfession("");
                    }
                    //数据是使用Intent返回
                    Intent intent = new Intent();
                    intent.putExtra("userJob", userJob);
                    //设置返回数据
                    UpdateJobActivity.this.setResult(RESULT_OK, intent);
                    //关闭Activity
                    UpdateJobActivity.this.finish();
                } else {
                    showShortToast1(result.getMsg());
                }
            }
            else{
                showShortToast1("连接超时");
            }
            closeWaitDialog();
        }
    }
}
